/*
 * @Author: your name
 * @Date: 2021-11-08 17:24:10
 * @LastEditTime: 2021-11-26 17:58:12
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \star-cat-h5\src\axios\ossUpload.js
 */
import md5 from "js-md5";
import OSS from 'ali-oss'

const devcontract = 'ost-app-img';
export function upload_img(files, success = () => {}, error = () => {}) {
    let file = new Blob([files], {
        type: files.type
    })
    let fileName = md5(files.name);
    let client = new OSS({
        region: 'oss-cn-beijing',
        accessKeyId: 'LTAI4GETVhjW9o7BMnChqVpk',
        accessKeySecret: 'ja5ArjSU3yFfiyVM2AXdfgmRwjeXEu',
        bucket: devcontract
    });
    let timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    let n = timestamp * 1000;
    let date = new Date(n);
    let dates = date.toJSON().substr(0, 10);
    let str = "/starcat/" + dates.replace(/-/g, "");
    // 添加文件后缀名
    let jptype = files.name.substr(files.name.lastIndexOf(".")).toLowerCase();
    let aliyunFileKey = str + "/" + fileName + Date.parse(new Date()) + jptype;
    const reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function (event) {
        const buffer = new OSS.Buffer(event.target.result);
        return client.put(aliyunFileKey, buffer).then(function (result) {
            let url = "https://" + devcontract + ".oss-cn-beijing.aliyuncs.com" + aliyunFileKey;
            console.log(url)
            success(url)
        }).catch(function (err) {
            console.log(err);
            error(err)
        });
    }

}